//
//  SNKBannerViewController.m
//  SleepNews
//
//  Created by Kavee DJ on 2016/12/9.
//  Copyright © 2016年 Kavee DJ. All rights reserved.
//

#import "SNKBannerViewController.h"
#import "SNKBannerData.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD+Extion.h"

@interface SNKBannerViewController ()<UIScrollViewDelegate>

@property (nonatomic , weak) UIScrollView *scrollView;
@property (nonatomic , weak) UILabel *titleLabel;
@property (nonatomic , weak) UILabel *countLabel;
@property (nonatomic , weak) UITextView *textview;

@property (nonatomic , assign) int count;
@property (nonatomic , copy) NSString *setname;

@property (nonatomic , strong) NSMutableArray *totalArray;

@property (nonatomic , weak) UIImageView *imageV;


@end

@implementation SNKBannerViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [self loadData];
}

- (void)setupUI {
    // 添加中间的SCrollView
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, SCREENW, SCREENH - 49 - 20)];
    scrollView.backgroundColor = [UIColor blackColor];
    scrollView.delegate = self;
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    
    // 添加返回按钮
    UIButton *backBtn = [[UIButton alloc] init];
    backBtn.frame = CGRectMake(5, 25, 40, 40);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"weather_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    // 下载按钮
    UIButton *downloadBtn = [[UIButton alloc] init];
    downloadBtn.frame = CGRectMake(SCREENW - 5 - 40, backBtn.kdj_y, 40, 40);
    [downloadBtn setBackgroundImage:[UIImage imageNamed:@"arrow237"] forState:UIControlStateNormal];
    [downloadBtn addTarget:self action:@selector(downClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:downloadBtn];
    
    // 标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.frame = CGRectMake(5, SCREENH - 70 - 49, SCREENW - 55, 20);
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:19];
    [self.view addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    // 数量
    UILabel *countLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(titleLabel.frame) + 5, titleLabel.kdj_y, 50, 15)];
    countLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:countLabel];
    self.countLabel = countLabel;
    
    // 内容
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(5, CGRectGetMaxY(titleLabel.frame), SCREENW - 15, 60)];
    textView.editable = NO;
    textView.font = [UIFont systemFontOfSize:14];
    textView.textAlignment = NSTextAlignmentLeft;
    textView.textColor = [UIColor whiteColor];
    textView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:textView];
    self.textview = textView;
}

- (void)loadData {
    IMP_BLOCK_SELF(SNKBannerViewController);
    
    [[KDJHttpTool shareHttpTool] runRequestWithParameters:nil path:_url success:^(id responseObject) {
        block_self.count = [responseObject[@"imgsum"] intValue]; // 图片数量
        block_self.setname = responseObject[@"setname"]; // 标题
        
        NSArray *dataArray = [SNKBannerData mj_objectArrayWithKeyValuesArray:responseObject[@"photos"]];
        
        // 创建frame模型对象
        NSMutableArray *statusFrameArray = [NSMutableArray array];
        
        for (SNKBannerData *data in dataArray) {
            [statusFrameArray addObject:data];
        }
        [block_self.totalArray addObjectsFromArray:statusFrameArray];
        
        [block_self setLabel];
        [block_self setImageView];
        
    } failure:^(id error) {
        
    }];
}

- (void)setLabel {
    // 标题
    self.titleLabel.text = self.setname;
    // 数量
    if (self.count > 1) {
        NSString *countNum = [NSString stringWithFormat:@"1/%d", self.count];
        self.countLabel.text = countNum;
    }
    // 内容
    [self setContentWithIndex:0];
}

#pragma mark - Private Method
- (void)setContentWithIndex:(int)index {
    NSString *content = [self.totalArray[index] note];
    NSString *contentTitle = [self.totalArray[index] imgtitle];
    if (content.length != 0) {
        self.textview.text = content;
    } else {
        self.textview.text = contentTitle;
    }
}

- (void)setImageView
{
    NSUInteger count = self.count;
    
    for (NSUInteger i = 0; i < count; i++) {
        CGFloat imageH = self.scrollView.kdj_height - 100;
        CGFloat imageW = self.scrollView.kdj_width;
        CGFloat imageY = 0;
        CGFloat imageX = i * imageW;
        UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
        
        // 图片显示的格式为合适大小
        imgV.contentMode = UIViewContentModeCenter;
        imgV.contentMode = UIViewContentModeScaleAspectFit;
        [self.scrollView addSubview:imgV];
    }
    
    [self setImgWithIndex:0];
    
    self.scrollView.contentOffset = CGPointZero;
    self.scrollView.contentSize = CGSizeMake(self.scrollView.kdj_width * count, 0);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
}

#pragma - UIScrollView Delegate
/** 滚动完毕时调用 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    int index = self.scrollView.contentOffset.x / self.scrollView.kdj_width;
    // 添加图片
    [self setImgWithIndex:index];
    
    // 添加文字
    NSString *countNum = [NSString stringWithFormat:@"%d/%d",index+1,self.count];
    self.countLabel.text = countNum;
    
    // 添加内容
    [self setContentWithIndex:index];
}

- (void)setImgWithIndex:(int)i
{
    UIImageView *photoImgView = nil;
    if (i == 0) {
        photoImgView = self.scrollView.subviews[i+2];
    }else{
        photoImgView = self.scrollView.subviews[i];
    }

    NSURL *purl = [NSURL URLWithString:[self.totalArray[i] imgurl]];
    
    // 如果这个相框里还没有照片才添加
//    if (photoImgView.image == nil) {
        [photoImgView sd_setImageWithURL:purl placeholderImage:nil];
        self.imageV = photoImgView;
//    } else 
}

#pragma mark - Action
- (void)downClick {
    KLog(@"%@", self.imageV.image)
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要保存到相册吗" preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIImageWriteToSavedPhotosAlbum(self.imageV.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error != NULL) {
        [MBProgressHUD showError:@"下载失败"];
    } else {
        [MBProgressHUD showSuccess:@"保存成功"];
    }
}

- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController setNavigationBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

#pragma mark - Getter and Setter 
-(NSMutableArray *)totalArray
{
    if (!_totalArray) {
        _totalArray = [NSMutableArray array];
    }
    return _totalArray;
}


@end
